package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	"github.com/valyala/fasthttp"
	"strconv"
	"strings"
	"time"
)

type MerchantController struct{}
type MerchantParam struct {
	Id           string `json:"id"`
	OperatorName string `json:"operator_name"`
	Page         int    `json:"page"`
	PageSize     int    `json:"page_size"`
}

// 渠道列表
func (that *MerchantController) MerchantList(ctx *fasthttp.RequestCtx) {

	param := MerchantParam{}

	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.Page < 1 {
		param.Page = 1
	}
	if param.PageSize < 10 || param.PageSize > 10000 {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	s, err := model.GetMerchantList(param.Page, param.PageSize, param.Id, param.OperatorName, ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	//获取三方游戏列表
	platform, err := model.GetPlatformByPid("0")

	platformList := map[string]model.Platform{}
	for _, value := range platform {
		platformList[value.ID] = value
	}
	//loginUser := model.GetLoginUser(ctx)
	for key, value := range s.D {
		apiFeeRate := map[string]float64{}
		json.Unmarshal([]byte(value.ApiFee), &apiFeeRate)

		newApiFee := []model.ApiFee{}
		for _, v := range platform {
			newApiFee = append(newApiFee, model.ApiFee{
				GameId:   v.ID,
				GameName: v.Name,
				Rate:     apiFeeRate[v.ID],
			})
		}
		jsonBytes, _ := json.Marshal(newApiFee)
		(s.D)[key].ApiFee = string(jsonBytes)
		//if loginUser.Businsess != "" {
		(s.D)[key].Password = ""
		(s.D)[key].Seamo = ""
		//}
	}
	helper.RetData(ctx, true, s)
}

func (that *MerchantController) ToMerchant(ctx *fasthttp.RequestCtx) {
	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Id == "" {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	merchant, err := model.GetOperatorInfoById(param.Id)
	token, err := session.AdminSet("merchant", merchant.Id, merchant.OperatorName, merchant.Password)

	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	rsp := model.MerchantLoginResp{
		Token:           token,
		OperatorName:    merchant.OperatorName,
		Id:              merchant.Id,
		Date:            time.Now().Unix(),
		WithdrawButton:  merchant.WithdrawButton,
		AccountSecurity: merchant.AccountSecurity,
		Seamo:           "",
		CodeUrl:         "",
	}
	helper.RetData(ctx, true, rsp)
}

// 关联渠道列表
func (that *MerchantController) MerchantExtendList(ctx *fasthttp.RequestCtx) {

	id := ctx.QueryArgs().GetUintOrZero("id")
	s, err := model.GetExtendMerchant(id)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, s)
}

// 额度管理
func (that *MerchantController) QuotaManage(ctx *fasthttp.RequestCtx) {
	param := model.OperatorQuoteParam{}

	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Page < 1 {
		param.Page = 1
	}
	if param.PageSize < 10 || param.PageSize > 3000 {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	data, err := model.GetOpeartorQuoteList(param, ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, data)
}

// 业务员对账表
func (this *MerchantController) BusinessSettle(ctx *fasthttp.RequestCtx) {
	param := model.ReportApiFeeParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	param.IsOperator = ctx.QueryArgs().GetUintOrZero("is_operator")
	param.IsBusiness = ctx.QueryArgs().GetUintOrZero("is_business")

	param.ExportExcel = ctx.QueryArgs().GetUintOrZero("export_excel")

	if param.ExportExcel == 1 {
		param.Page = 1
		param.PageSize = model.ExportExcelPageSize
	}

	if param.Page < 1 {
		param.Page = 1
	}

	data, err := model.ReportApiFeeList(param, ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	if param.ExportExcel == 1 {
		exportData := [][]interface{}{}
		for _, value := range data.D {
			single := []interface{}{
				value.OperatorId,
				value.OperatorName,
				value.BusinessId,
				value.BusinessName,
				value.Deposit,
				value.DepositFee,
				value.Withdraw,
				value.WithdrawFee,
				value.ApiFee,
				value.TotalProfit,
			}
			exportData = append(exportData, single)
		}
		exportTitle := []string{
			"所属渠道ID",
			"所属渠道名称",
			"业务员ID",
			"业务员名称",
			"总充值",
			"充值手续费",
			"总提现",
			"提现手续费",
			"API费用",
			"总利润",
		}
		filename := "渠道对账表-" + time.Now().Format("20060102150405")
		if model.ExportExcel(filename, exportTitle, exportData) == nil {
			helper.RetData(ctx, true, filename)
		} else {
			helper.RetData(ctx, false, helper.RequestFail)
		}
		return
	} else {
		helper.RetData(ctx, true, data)
		return
	}
}

// 新增编辑
func (that *MerchantController) MerchantUpdate(ctx *fasthttp.RequestCtx) {

	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("渠道新增更新操作", ctx)
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	//api费用
	platform, _ := model.GetPlatformByPid("0")
	AddApiFee := strings.Split(param.ApiFee, ",")
	newFeeRate := map[string]float64{}
	for k, v := range platform {
		if len(AddApiFee) < k+1 {
			newFeeRate[v.ID] = 0
		} else {
			floatFee, _ := strconv.ParseFloat(AddApiFee[k], 64)
			newFeeRate[v.ID] = floatFee
		}

	}
	jsonBytes, _ := json.Marshal(newFeeRate)
	param.ApiFee = string(jsonBytes)

	err = model.MerchantUpdate(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "succeed")
}

func (that *MerchantController) MerchantUpdateOfficial(ctx *fasthttp.RequestCtx) {

	//param := model.TblOperatorInfo{}
	//err := json.Unmarshal(ctx.PostBody(), &param)
	//if err != nil {
	//
	//	helper.RetData(ctx, false, "参数错误")
	//	return
	//}
	model.InsertLog("一键同步官方配置", ctx)

	err := model.MerchantUpdateOfficial(ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "succeed")
}

func (that *MerchantController) MerchantUpdateOfficialPP(ctx *fasthttp.RequestCtx) {

	//param := model.TblOperatorInfo{}
	//err := json.Unmarshal(ctx.PostBody(), &param)
	//if err != nil {
	//
	//	helper.RetData(ctx, false, "参数错误")
	//	return
	//}
	model.InsertLog("一键同步PP官方配置", ctx)

	err := model.MerchantUpdateOfficialPP(ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "succeed")
}

func (that *MerchantController) MerchantUpdateOfficial2(ctx *fasthttp.RequestCtx) {

	//param := model.TblOperatorInfo{}
	//err := json.Unmarshal(ctx.PostBody(), &param)
	//if err != nil {
	//
	//	helper.RetData(ctx, false, "参数错误")
	//	return
	//}
	model.InsertLog("一键同步官方掉绑配置", ctx)

	err := model.MerchantUpdateOfficial2(ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "succeed")
}

func (that *MerchantController) ApifeePlist(ctx *fasthttp.RequestCtx) {
	data := ""
	//获取三方游戏列表
	platform, _ := model.GetPlatformByPid("0")
	for _, value := range platform {
		if data == "" {
			data = value.Name
		} else {
			data = data + "," + value.Name
		}
	}
	helper.RetData(ctx, true, data)
	return
}

// 渠道api费用
func (that *MerchantController) ApifeeUpdate(ctx *fasthttp.RequestCtx) {
	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("渠道api费用编辑", ctx)
	admin := session.AdminGet(ctx)

	newFeeRate := []model.ApiFee{}
	json.Unmarshal([]byte(param.ApiFee), &newFeeRate)
	apiFeeRate := map[string]float64{}
	for _, v := range newFeeRate {
		apiFeeRate[v.GameId] = v.Rate

	}
	jsonBytes, _ := json.Marshal(apiFeeRate)
	param.ApiFee = string(jsonBytes)
	err = model.ChannelApifeeUpdate(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

type OnekeyToFakepgRate struct {
	Rate int `cbor:"rate" json:"rate"`
}

func (that *MerchantController) OnekeyToFakepg(ctx *fasthttp.RequestCtx) {
	param := OnekeyToFakepgRate{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Rate > 100 {
		param.Rate = 100
	}
	if param.Rate < 0 {
		param.Rate = 0
	}
	err = model.UpdateOnekeyToFakepg(param.Rate)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *MerchantController) MerchantToken(ctx *fasthttp.RequestCtx) {

	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	merchant, _ := model.GetOperatorInfoById(admin["id"])
	if merchant.Id == "" {
		helper.RetData(ctx, false, "权限不足")
	}
	//清除token
	session.AdminClear(ctx)

	//构造token
	token, err := session.AdminSet("merchant", merchant.Id, merchant.OperatorName, merchant.Password)

	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	rsp := model.MerchantLoginResp{
		Token:           token,
		OperatorName:    merchant.OperatorName,
		Id:              merchant.Id,
		Date:            time.Now().Unix(),
		WithdrawButton:  merchant.WithdrawButton,
		AccountSecurity: merchant.AccountSecurity,
		Seamo:           "",
		CodeUrl:         "",
	}
	helper.RetData(ctx, true, rsp)
}

func (that *MerchantController) ChangeAllPassword(ctx *fasthttp.RequestCtx) {

	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "admin" {
		helper.RetData(ctx, false, "权限不足")
		return
	}

	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	param.Password, _ = model.Encrypt(param.Password)
	err = model.UpdateOperatorPassword("", param.Password)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}

func (that MerchantController) ChannelWagedList(ctx *fasthttp.RequestCtx) {
	param := model.ChannelWagedParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil || param.ChannelId < 100000 || param.ChannelId > 999999 {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	s, err := model.GetChannelWagedList(param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, s)
}

func (that MerchantController) UpdateChannelWaged(ctx *fasthttp.RequestCtx) {
	param := model.ChannelWagedTable{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil || param.ChannelId < 100000 || param.ChannelId > 999999 {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("渠道打码配置编辑", ctx)
	err = model.UpdateChannelWaged(param, 0)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}

func (that MerchantController) DeleteChannelWaged(ctx *fasthttp.RequestCtx) {
	param := model.ChannelWagedTable{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("渠道打码配置删除", ctx)
	err = model.UpdateChannelWaged(param, 1)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}
